import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:gw_github_flutter/common/global.dart';
import 'package:gw_github_flutter/common/gwNet.dart';
import 'package:gw_github_flutter/common/notifier.dart';
import 'package:gw_github_flutter/generated/l10n.dart';
import 'package:gw_github_flutter/models/user.dart';
import 'package:gw_github_flutter/route/login/gwGet_codeView.dart';
import 'package:provider/provider.dart';

class LoginRoute extends StatefulWidget {
  const LoginRoute({Key? key}) : super(key: key);

  @override
  State<LoginRoute> createState() => _LoginRouteState();
}

class _LoginRouteState extends State<LoginRoute> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  bool pwdShow = false;
  GlobalKey _formKey = GlobalKey<FormState>();
  bool _nameAutoFocus = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _unameController.text = Global.profile.lastLogin ?? "";
    if (_unameController.text.isNotEmpty) {
      _nameAutoFocus = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    var gwLocal = S.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(gwLocal.login),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(
            children: [
              TextFormField(
                autofocus: _nameAutoFocus,
                controller: _unameController,
                decoration: InputDecoration(
                    labelText: gwLocal.login,
                    hintText: gwLocal.login,
                    prefixIcon: Icon(Icons.person)),
                validator: (value) {
                  return (value == null || value.trim().isNotEmpty)
                      ? null
                      : "不能为null";
                },
              ),
              TextFormField(
                controller: _pwdController,
                autofocus: !_nameAutoFocus,
                decoration: InputDecoration(
                  labelText: gwLocal.pwd,
                  hintText: gwLocal.pwd,
                  prefixIcon: Icon(Icons.lock),
                  suffixIcon:
                      // Expanded(
                      //   child:
                      Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      GwGetCodeView(
                        available: true,
                        onTapCallback: (){
                          
                        },),
                      IconButton(
                        icon: Icon(
                            pwdShow ? Icons.visibility_off : Icons.visibility),
                        onPressed: () {
                          setState(() {
                            pwdShow = !pwdShow;
                          });
                        },
                      ),
                    ],
                  ),
                ),
                obscureText: !pwdShow,
                validator: (value) {
                  return value == null || value.trim().isNotEmpty
                      ? null
                      : "密码错误";
                },
              ),
              Padding(
                padding: EdgeInsets.only(top: 25),
                child: ConstrainedBox(
                  constraints: BoxConstraints.expand(height: 55.0),
                  child: ElevatedButton(
                    // color: Theme.of(context).primaryColor,
                    onPressed: _onLogin,
                    // textColor: Colors.white,
                    child: Text(gwLocal.login),
                  ),
                ),
              ),
              /// Or 横线
                Padding(
                    padding: const EdgeInsets.only(top: 20.0),
                    child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
                      Container(
                          width: 100.0,
                          height: 1.0,
                          decoration: const BoxDecoration(
                            gradient: LinearGradient(colors: [Colors.black12, Colors.black]),
                          )),
                      const Padding(
                          padding: EdgeInsets.only(left: 15.0, right: 15.0),
                          child: Text('Or', style: TextStyle(fontSize: 16, color: Colors.black))),
                      Container(
                          width: 100.0,
                          height: 1.0,
                          decoration: const BoxDecoration(
                            gradient: LinearGradient(colors: [Colors.black, Colors.black12]),
                          ))
                    ])),

                /// 第三方登录按钮
                Padding(
                    padding: const EdgeInsets.only(top: 5.0),
                    child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
                      IconButton(
                        color: Colors.blue,
                          icon: const Icon(FontAwesome.weixin),
                          onPressed: () {
                            EasyLoading.showToast("微信");
                          },
                          iconSize: 25.0),
                      SizedBox(width: 40.0),
                      IconButton(
                          icon: const Icon(FontAwesome.qq),
                          onPressed: () {
                            EasyLoading.showToast("qq");
                          },
                          iconSize: 25.0),
                    ]))
            ],
          ),
        ),
      ),
    );
  }

  _onLogin() async {
    if ((_formKey.currentState as FormState).validate()) {
      EasyLoading.show(status: 'loading...');
      User? user;
      try {
        user = await GwNet(context)
            .login(_unameController.text, _pwdController.text);
        // 因为登录页返回后，首页会build，所以我们传false，更新user后不触发更新
        Provider.of<UserModel>(context, listen: false).user = user;
      } on DioError catch (e) {
        //登录失败则提示
        if (e.response?.statusCode == 401) {
          EasyLoading.showToast("登录失败");
        } else {
          EasyLoading.showToast(e.toString());
        }
      } finally {
        // 隐藏loading框
        EasyLoading.dismiss();
      }
    }
  }
}
